﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraPrinting;

using MM.Entities;
using MM.Business;

using System.Devices;// rapi2.dll

namespace MM
{
    public partial class frmTaoPhieuXK_GiaCong : Form
    {
        string _matau = "";
        string _nguoitao = "";
        string _sConn = "";
        string _plant = "";
        List<TON_KHO> lstTonKho = new List<TON_KHO>();
        List<CHI_TIET_PXH> lstCTpxh = new List<CHI_TIET_PXH>();
        RemoteDevice rdev = null;

        public frmTaoPhieuXK_GiaCong(string sConn)
        {
            InitializeComponent();
            _sConn = sConn;

            _matau = frmDangNhap.objTau._tenTau2KiTu;
            _plant = frmDangNhap.objTau._plantReferenceSAP;
            _nguoitao = frmDangNhap.objTaiKhoan._soCMND;



            this.gridControl2.DataSource = lstCTpxh;
            this.HienthiPHIEU_DAT_HANG_MAX(_matau);
            this.HienthiCHI_TIET_PDH(this.txtSoPhieuPO.Text);
            this.txtNgayThucHien.Text = DateTime.Today.Day.ToString() + "/" + DateTime.Today.Month.ToString() + "/" + DateTime.Today.Year.ToString();
            this.txtNguoiThucHien.Text = _nguoitao;

           
        }

        private void InitKho(string mavtpt)
        {
            clsKHO khoCtrl = new clsKHO(_sConn);
            List<KHO> lst = new List<KHO>();
            lst = khoCtrl.usp_SelectKHO_ByMaVTPT_TON_KHO(mavtpt);
            
            this.lookUpKho.Properties.DataSource = lst;
            this.lookUpKho.Properties.DisplayMember = "TenKho";
            this.lookUpKho.Properties.ValueMember = "MaKho";
        }


        private void HienthiPHIEU_DAT_HANG_MAX(string matau)
        {
            clsPHIEU_DAT_HANG pdhCtrl = new clsPHIEU_DAT_HANG(_sConn);
            List<PHIEU_DAT_HANG> lst = new List<PHIEU_DAT_HANG>();
            lst = pdhCtrl.usp_SelectPHIEU_DAT_HANG_MAX(matau);
            if (lst.Count > 0)
            {
                this.txtSoPhieuPO.Text = lst[0].POThamChieuSAP;
                this.txtPlant.Text = lst[0].PlanReferenceSAP.Trim();
                this.txtPlantGui.Text = lst[0].PlantGui.Trim();

                if (lst[0].LoaiPO == "UB") // lenh chuyen kho
                {
                    this.chkPOSTO.Checked = true;
                    if (this.txtPlantGui.Text.Trim() == _plant)
                        this.cmdLuu.Enabled = true;
                    else
                        this.cmdLuu.Enabled = false;
                }
                else
                    this.chkPOSTO.Checked = false;
                
            }
        }

        private void HienthiPHIEU_DAT_HANG(string POThamChieuSAP)
        {
            clsPHIEU_DAT_HANG pdhCtrl = new clsPHIEU_DAT_HANG(_sConn);
            List<PHIEU_DAT_HANG> lst = new List<PHIEU_DAT_HANG>();
            lst = pdhCtrl.usp_SelectPHIEU_DAT_HANG(POThamChieuSAP);
            if (lst.Count > 0)
            {
                this.txtSoPhieuPO.Text = lst[0].POThamChieuSAP;
                this.txtPlant.Text = lst[0].PlanReferenceSAP.Trim();
                this.txtPlantGui.Text = lst[0].PlantGui.Trim();

                if (lst[0].LoaiPO == "UB") // lenh chuyen kho
                {
                    this.chkPOSTO.Checked = true;
                    if (this.txtPlantGui.Text.Trim() == _plant)
                        this.cmdLuu.Enabled = true;
                    else
                        this.cmdLuu.Enabled = false;
                }
                else
                    this.chkPOSTO.Checked = false;
            }
        }

        private void HienthiCHI_TIET_PDH(string POThamChieuSAP)
        {
            clsCHI_TIET_PDH ctCtrl = new clsCHI_TIET_PDH(_sConn);
            List<CHI_TIET_PDH> lstCT = new List<CHI_TIET_PDH>();

            lstCT = ctCtrl.usp_SelectCHI_TIET_PDHByPOThamChieuSAP(POThamChieuSAP);
            

            if (this.chkPOSTO.Checked == false) // xuat kho di gia cong
            {
                List<CHI_TIET_PDH> lstCTCom = new List<CHI_TIET_PDH>();

                lstCT.RemoveAll(delegate(CHI_TIET_PDH x) { return (x.MaTrangThai != 1 || x.TinhTrang == 1); });

                clsCHI_TIET_PDH_COMPONENT comCtrl = new clsCHI_TIET_PDH_COMPONENT(_sConn);
                List<CHI_TIET_PDH_COMPONENT> lstCom;
                CHI_TIET_PDH oCTPDH;
                for (int i = 0; i < lstCT.Count; i++)
                {
                    lstCom = new List<CHI_TIET_PDH_COMPONENT>();
                    lstCom = comCtrl.SelectCHI_TIET_PDH_COMPONENT(lstCT[i].MaChiTiet);

                    for (int j = 0; j < lstCom.Count; j++)
                    {
                        oCTPDH = new CHI_TIET_PDH();
                        oCTPDH.MaThietBi = lstCom[j].MaThietBi;
                        //oCTPDH.MaTrangThai = lstCT[i].MaTrangThai;
                        oCTPDH.MaTrangThai = 2;
                        oCTPDH.TenTrangThai = lstCT[i].TenTrangThai;
                        oCTPDH.SoLuong = lstCom[j].SoLuong;
                        oCTPDH.TenVTPT = lstCom[j].TenThietBi;
                        oCTPDH.POItem_No = lstCT[i].POItem_No;
                        lstCTCom.Add(oCTPDH);
                    }
                }
                this.gridControl1.DataSource = lstCTCom;
            }            
            else
                this.gridControl1.DataSource = lstCT;
        }

        private void cmdLuu_Click(object sender, EventArgs e)
        {
            if (chkPOSTO.Checked == true) // lenh chuyen kho
            {
                if (this.txtPlantGui.Text.Trim() != _plant)
                {
                    MessageBox.Show("LỆNH CHUYỂN KHO KHÁC VỚI PLANT HIỆN TẠI");
                    return;
                }
            }

            PHIEU_XUAT_HANG oPXH = new PHIEU_XUAT_HANG();
            oPXH.NgayXuat = DateTime.Today;
            oPXH.NguoiXuat = _nguoitao;
            oPXH.PlantReferenceSAP = this.txtPlant.Text;
            oPXH.MaTau = _matau;
           
           
            if (lstCTpxh.Count > 0)
            {
                clsPHIEU_XUAT_HANG pxhCtrl = new clsPHIEU_XUAT_HANG(_sConn);
                string maphieuxuathang = pxhCtrl.InsertPHIEU_XUAT_HANG(oPXH, lstCTpxh);
                if (maphieuxuathang != "")
                {
                    this.txtSoPhieuGI.Text = maphieuxuathang;

                    this.lstCTpxh.RemoveAll(delegate(CHI_TIET_PXH x) { return x.TinhTrang == 0; });

                    if (lstCTpxh.Count > 0)
                    {
                        MessageBox.Show("KHÔNG XUẤT KHO ĐƯỢC CHO CÁC VTPT CÒN LẠI TRONG DS\nLÝ DO:\n - HOẶC VTPT KHÔNG CÓ TRONG PO \n - HOẶC SỐ LƯỢNG XUẤT LỚN HƠN SỐ LƯỢNG TRONG PO");
                    }
                    this.gridControl2.RefreshDataSource();
                }
                else
                    MessageBox.Show("LƯU DỮ LIỆU KHÔNG THÀNH CÔNG");
            }
        }

        private void gridDSVT_Click(object sender, EventArgs e)
        {
            GridView view = (GridView)sender;
            GridHitInfo info = view.CalcHitInfo(gridControl1.PointToClient(MousePosition));

            if (info.InRow || info.InRowCell)
            {
                this.cmdCapNhatSL.Enabled = false;
                string mathietbi = ((CHI_TIET_PDH)this.gridDSVT.GetFocusedRow()).MaThietBi;
                this.txtSoluongXuat.Text = (((CHI_TIET_PDH)this.gridDSVT.GetFocusedRow()).SoLuong.ToString());
                this.InitKho(mathietbi);
            }

        }

        private void cmdCapNhatSL_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.txtSoPhieuPO.Text == "")
                {
                    MessageBox.Show("VUI LÒNG ĐIỀN SỐ PO");
                    return;
                }
                
                float soluongton=float.Parse(this.txtSoLuongTon.Text.Trim());
                float soluong = 0;
                try
                {
                    soluong = float.Parse(this.txtSoluongXuat.Text.Trim());
                }
                catch { MessageBox.Show("VUI LÒNG ĐIỀN SỐ LƯỢNG CẦN XUẤT"); }

                float soluongPO = float.Parse(((CHI_TIET_PDH)this.gridDSVT.GetFocusedRow()).SoLuong.ToString());


                if (soluong > soluongPO)
                {
                    MessageBox.Show("SỐ LƯỢNG XUẤT PHẢI NHỎ HƠN HOẶC BẰNG SỐ LƯỢNG PO");
                    return;
                }

                if (soluong <= soluongton)
                {
                    float tongsoluong = soluong;                    
                    for (int j = 0; j < lstCTpxh.Count; j++)
                    {
                        tongsoluong += lstCTpxh[j].SoLuong;
                    }
                    if (tongsoluong <= soluongPO)
                    {
                        CHI_TIET_PXH oCTPXH = new CHI_TIET_PXH();
                        oCTPXH.MaThietBi = ((CHI_TIET_PDH)this.gridDSVT.GetFocusedRow()).MaThietBi;
                        oCTPXH.TenVTPT = ((CHI_TIET_PDH)this.gridDSVT.GetFocusedRow()).TenVTPT;
                        if (chkPOSTO.Checked == true)// lenh chuyen kho
                            oCTPXH.MaTrangThai = int.Parse(((CHI_TIET_PDH)this.gridDSVT.GetFocusedRow()).MaTrangThai.ToString());
                        else
                            oCTPXH.MaTrangThai = 2;
                        oCTPXH.MaKho = lookUpKho.GetColumnValue("MaKho").ToString();
                        oCTPXH.SoLuong = soluong;
                        oCTPXH.POThamChieuSAP = this.txtSoPhieuPO.Text;
                        oCTPXH.MaChiTietPDH = ((CHI_TIET_PDH)this.gridDSVT.GetFocusedRow()).POItem_No;

                        int index = lstCTpxh.FindIndex(delegate(CHI_TIET_PXH x) { return x.MaThietBi == oCTPXH.MaThietBi && x.MaKho==oCTPXH.MaKho && x.MaTrangThai==oCTPXH.MaTrangThai; });

                        if (index >= 0)
                        {
                            lstCTpxh[index].SoLuong += oCTPXH.SoLuong;
                        }
                        else
                            lstCTpxh.Add(oCTPXH);

                        this.gridControl2.RefreshDataSource();

                        soluongton -= soluong;
                        this.txtSoLuongTon.Text = soluongton.ToString();
                     
                    }
                    else
                    {
                        MessageBox.Show("TỔNG SỐ LƯỢNG XUẤT PHẢI NHỎ HƠN HOẶC BẰNG SỐ LƯỢNG TRÊN LỆNH XUẤT KHO (SỐ LƯỢNG TRÊN PO GIA CÔNG)");
                    }
                }
                else
                {
                    MessageBox.Show("SỐ LƯỢNG XUẤT PHẢI NHỎ HƠN HOẶC BẰNG SỐ LƯỢNG TỒN KHO");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

       

        private void lookUpKho_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
        {
            try
            {
                float soluongmax = 0;
                string makho = lookUpKho.GetColumnValue("MaKho").ToString();
                string mavtpt = ((CHI_TIET_PDH)this.gridDSVT.GetFocusedRow()).MaThietBi;
                int matrangthai = int.Parse(((CHI_TIET_PDH)this.gridDSVT.GetFocusedRow()).MaTrangThai.ToString());
                clsTON_KHO tonCtrl = new clsTON_KHO(_sConn);
                List<TON_KHO> lstton = new List<TON_KHO>();
                lstton = tonCtrl.usp_SelectTON_KHO_ByMaKho(makho, mavtpt, matrangthai, null, null);
                for (int i = 0; i < lstton.Count; i++)
                {
                    soluongmax += lstton[i].SoLuong;
                }

                // kiem tra xem VTPT nay co cac phieu xuat kho nao chua duoc duyet
                List<CHI_TIET_PXH> lstctpxh = new List<CHI_TIET_PXH>();
                clsCHI_TIET_PXH ctpxhCtrl = new clsCHI_TIET_PXH(_sConn);
                if (chkPOSTO.Checked==true) // lenh chuyen kho
                    lstctpxh = ctpxhCtrl.usp_CheckSoLuongXuatKhoChuaDuyet(mavtpt, makho, matrangthai);
                else
                    lstctpxh = ctpxhCtrl.usp_CheckSoLuongXuatKhoChuaDuyet(mavtpt, makho, 2);

                for (int i = 0; i < lstctpxh.Count; i++)
                {
                    soluongmax -= lstctpxh[i].SoLuong;
                }

                if (lstctpxh.Count > 0)
                {
                    if (MessageBox.Show("TỒN TẠI MỘT SỐ PHIẾU XUẤT KHO LIÊN QUAN ĐẾN VPTP " + mavtpt + "\n BẠN CÓ MUỐN XEM ?", "THÔNG BÁO", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        CHI_TIET_PXH oTim = new CHI_TIET_PXH();
                        oTim.MaThietBi = mavtpt;
                        frmHienthiPhieuXK frm = new frmHienthiPhieuXK(_sConn, lstctpxh[0].MaPhieuXuatHang);
                        frm.TimKiem(oTim, 0);
                        frm.Show(this);
                    }
                }

                // kiem tra xem VTPT nay da ton tai trong list can xuat kho chua
                for (int i = 0; i < lstCTpxh.Count; i++)
                {
                    if (lstCTpxh[i].MaThietBi == mavtpt && lstCTpxh[i].MaKho == makho)
                        soluongmax -= lstCTpxh[i].SoLuong;
                }

                this.txtSoLuongTon.Text = soluongmax.ToString();
                this.cmdCapNhatSL.Enabled = true;
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
                this.cmdCapNhatSL.Enabled = false;
            }
        }

        private void label3_Click(object sender, EventArgs e)
        {
            frmTimPhieuDH f = new frmTimPhieuDH(_sConn);
            f.chonPDH += new frmTimPhieuDH.ChonPhieuDatHang(GetPhieuDatHang);
            f.Show(this);
        }

        private void GetPhieuDatHang(object sender, ChonPhieuDHEventArgs e)
        {
            HienthiPHIEU_DAT_HANG(e.POThamChieuSAP);
            HienthiCHI_TIET_PDH(e.POThamChieuSAP);


        }

        private void txtSoPhieuPO_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.lstCTpxh.Clear();
                this.gridControl2.RefreshDataSource();
                this.InitKho("");
                this.txtSoLuongTon.Text = "";

                if (this.txtSoPhieuPO.Text.Trim().Length == 10)
                {                                   
                    string POThamChieuSAP = this.txtSoPhieuPO.Text.Trim();
                    this.HienthiPHIEU_DAT_HANG(POThamChieuSAP);
                    this.HienthiCHI_TIET_PDH(POThamChieuSAP);
                }
                else
                {
                    this.txtSoPhieuPO.BackColor = Color.Red;
                }

            }
        }

        

        private void frmTaoPhieuXK_GiaCong_Load(object sender, EventArgs e)
        {
            Common.SetColor(this);
        }

        private void InitPrinter()
        {
            DevExpress.XtraPrinting.PrintableComponentLink pl = new DevExpress.XtraPrinting.PrintableComponentLink();
            pl.Component = gridControl1;
            pl.Margins.Left = 50;
            pl.Margins.Right = 50;
            pl.CreateMarginalHeaderArea += new CreateAreaEventHandler(Link_CreateMarginalHeaderArea);            
            printingSystem1.Links.Add(pl);            
           
            pl.ShowPreview();           
            
        }

        private void Link_CreateMarginalHeaderArea(object sender, CreateAreaEventArgs e)
        {
            string headerColumn = "DANH SÁCH VẬT TƯ CẦN XUẤT KHO ";
            if (chkPOSTO.Checked == true)// lenh chuyen kho
                headerColumn += "ĐỂ CHUYỂN KHO KHÁC PLANT";
            else
                headerColumn += "ĐỂ ĐI GIA CÔNG";
           
            e.Graph.StringFormat = new BrickStringFormat(StringAlignment.Center);
            e.Graph.Font = new Font("Tahoma", 14, FontStyle.Bold);
            RectangleF rec = new RectangleF(0, 25, e.Graph.ClientPageSize.Width, 50);
            e.Graph.DrawString(headerColumn, Color.Black, rec, BorderSide.None);

        }
        private void printPreviewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (!gridControl1.IsPrintingAvailable)
                {
                    MessageBox.Show("The 'DevExpress.XtraPrinting' library is not found", "Error");
                    return;
                }
                
                this.InitPrinter();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

       

        private void cmdNapDuLieu_Click(object sender, EventArgs e)
        {
            lstCTpxh.Clear();
            //try
            //{
            //    if (rdev != null)
            //    {

            //        string filenameD = "";
            //        string filenameS = "";
            //        clsTHAM_SO tsCtrl = new clsTHAM_SO(_sConn);
            //        THAM_SO tsObj = new THAM_SO();
            //        tsObj = tsCtrl.SelectTHAM_SO("vPXK_Des"); // duong dan luu file tren PC 

            //        if (tsObj != null && tsObj.DaXoa == 0)
            //        {
            //            filenameD = tsObj.GiaTri;
            //        }

            //        tsObj = tsCtrl.SelectTHAM_SO("vPXK_Src"); // duong dan file se copy tu may kiem kho
            //        if (tsObj != null && tsObj.DaXoa == 0)
            //        {
            //            filenameS = tsObj.GiaTri;
            //        }

            //        if (filenameD != "" && filenameS != "")
            //        {


            //            filenameD = filenameD + this.txtSoPhieuPO.Text.Trim() + "_" + this.cboFileName.Text;

            //            //string filenameS = rdev.GetFolderPath(SpecialFolder.MyDocuments) + @"\KiemKho\";// +this.cboFileName.Text;
            //            //filenameS = @"\Temp\KiemKho\";// +this.cboFileName.Text;




            //            RemoteFile.CopyFileFromDevice(rdev, filenameS + this.cboFileName.Text, filenameD, true);
            //            //RemoteFile.Copy(rdev, filenameS + this.cboFileName.Text, filenameS + "yen.txt", true);

            //            if (File.Exists(filenameD))
            //            {
            //                this.DocNoiDungFile(filenameD);
            //            }
            //        }

            //    }
            //    else
            //        MessageBox.Show("CHƯA KẾT NỐI ĐƯỢC THIẾT BỊ");
            //    //this.DocNoiDungFile(@"d:\4500000095_yen.txt");
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message);
            //}

            try
            {
                string filenameD = "";
                string filenameS = "";
                string filenameL = ""; // duong dan luu file da duoc doc noi dung
                clsTHAM_SO tsCtrl = new clsTHAM_SO(_sConn);
                THAM_SO tsObj = new THAM_SO();
                tsObj = tsCtrl.SelectTHAM_SO("vPXK_Des"); // duong dan luu file tren PC 

                if (tsObj != null && tsObj.DaXoa == 0)
                {
                    filenameD = tsObj.GiaTri;
                }

                tsObj = tsCtrl.SelectTHAM_SO("vPXK_Src"); // duong dan file se copy tu may kiem kho
                if (tsObj != null && tsObj.DaXoa == 0)
                {
                    filenameS = tsObj.GiaTri;
                }

                tsObj = tsCtrl.SelectTHAM_SO("vPXK_Des_Loaded"); // duong dan file se move tu Des vao Loaded
                if (tsObj != null && tsObj.DaXoa == 0)
                {
                    filenameL = tsObj.GiaTri;
                }

                if (filenameD != "" && filenameS != "" && filenameL != "")
                {


                    filenameD = filenameD + DateTime.Today.Year.ToString() + DateTime.Today.Month.ToString() + DateTime.Today.Day.ToString() + "_" + this.cboFileName.Text;

                    filenameS += this.cboFileName.Text;


                    RemoteFile.CopyFileFromDevice(rdev, filenameS, filenameD, true);

                    //rdev.Dispose();

                    if (File.Exists(filenameD))
                    {
                        RemoteFile.Delete(rdev, filenameS);
                        this.txtFileName.Text = this.CatNoiDungFile(filenameD, this.cboFileName.Text); // doc noi dung file và tách thành nhìu file tương ứng với MaKho - tức số cmnd của user 
                        if (this.txtFileName.Text != "") // cat thanh cong
                        {
                            lstTonKho.Clear();
                            this.gridControl1.DataSource = lstTonKho;
                            this.DocNoiDungFile(this.txtFileName.Text);

                            filenameL += DateTime.Today.Year.ToString() + DateTime.Today.Month.ToString() + DateTime.Today.Day.ToString() + "_" + this.cboFileName.Text;
                            File.Move(filenameD, filenameL);
                        }


                    }
                }
                else
                    MessageBox.Show("VUI LÒNG NHẬP GIÁ TRỊ THÔNG SỐ ĐƯỜNG DẪN: vPXK_Des,vPXK_Src,vPXK_Des_Loaded");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void DocNoiDungFile(string filename)
        {
            lstCTpxh.Clear();
            Stream r = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            StreamReader reader = new StreamReader(r);
            try
            {

                CHI_TIET_PXH tkObj;


                clsVAT_TU_PHU_TUNG vtptCtrl = new clsVAT_TU_PHU_TUNG(_sConn);
                VAT_TU_PHU_TUNG oVTPT = new VAT_TU_PHU_TUNG();
                clsTRANG_THAI_VTPT ttvtCtrl = new clsTRANG_THAI_VTPT(_sConn);
                TRANG_THAI_VTPT oTTVT = new TRANG_THAI_VTPT();
                string giatri = "";

                clsTHAM_SO tsCtrl = new clsTHAM_SO(_sConn);
                THAM_SO tsObj = new THAM_SO();
                tsObj = tsCtrl.SelectTHAM_SO("vPXK_Template");
                if (tsObj != null && tsObj.DaXoa == 0)
                {
                    giatri = tsObj.GiaTri;
                }

                if (giatri == "")
                {
                    MessageBox.Show("BẠN CHƯA NHẬP GIÁ TRỊ CHO THAM SỐ: vPXK_Template");
                    return;
                }

                int iMaKho = -1; // vị trí 
                int iMaVTPT = -1;
                int iSLQuet = -1;

                iMaKho = Array.IndexOf(giatri.Split(','), "MaKho");
                iMaVTPT = Array.IndexOf(giatri.Split(','), "MaVTPT");
                iSLQuet = Array.IndexOf(giatri.Split(','), "SLQuet");

                bool flag = true;
                while (!reader.EndOfStream)
                {

                    try
                    {

                        tkObj = new CHI_TIET_PXH();

                        string line = reader.ReadLine();
                        string[] arrvalue = new string[10];
                        arrvalue = line.Split('\t');


                        if (iMaKho > -1)
                        {
                            if (arrvalue[iMaKho] == _nguoitao)
                            {
                                flag = true;
                            }
                            else
                                flag = false;
                        }
                        else
                            flag = false;


                        if ((iMaKho > -1 && flag == true) || (iMaKho < 0 && flag == false))
                        {

                            #region Doc tung dong noi dung File


                            if (iMaVTPT > -1)
                            {
                                string[] arrBarCode = new string[4];
                                arrBarCode = arrvalue[iMaVTPT].Split('#');
                                if (arrBarCode[0] == "")// ma vtpt
                                {
                                    MessageBox.Show("MÃ VTPT BỊ TRỐNG");
                                    chkKhonghople.Checked = true;
                                    this.cmdLuu.Enabled = false;
                                    return;
                                }
                                tkObj.MaThietBi = arrBarCode[0];

                                if (arrBarCode[1] == "")// ma KHO
                                {
                                    MessageBox.Show("MÃ KHO BỊ TRỐNG");
                                    chkKhonghople.Checked = true;
                                    this.cmdLuu.Enabled = false;
                                    return;
                                }
                                tkObj.MaKho = arrBarCode[1];
                                if (arrBarCode[2] == "")// ma TRANG THAI
                                {
                                    MessageBox.Show("MÃ TRẠNG THÁI BỊ TRỐNG");
                                    chkKhonghople.Checked = true;
                                    this.cmdLuu.Enabled = false;
                                    return;
                                }
                                try
                                {
                                    tkObj.MaTrangThai = int.Parse(arrBarCode[2]);
                                }
                                catch
                                {
                                    MessageBox.Show("MÃ TRẠNG THÁI SAI ĐỊNH DẠNG");
                                    chkKhonghople.Checked = true;
                                    this.cmdLuu.Enabled = false;
                                    return;
                                }

                                oVTPT = new VAT_TU_PHU_TUNG();
                                oVTPT = vtptCtrl.SelectVAT_TU_PHU_TUNG(tkObj.MaThietBi.Trim(), frmDangNhap.objTau.maTau);
                                if (oVTPT != null && oVTPT._maVTPT != "")
                                {
                                    tkObj.TenVTPT = oVTPT._tenVTPT;
                                    chkKhonghople.Checked = false;
                                    this.cmdLuu.Enabled = true;
                                }
                                else
                                {
                                    tkObj.TenVTPT = "#KHÔNG TỒN TẠI DỮ LIỆU CHO VPTP NÀY";
                                    chkKhonghople.Checked = true;
                                    this.cmdLuu.Enabled = false;
                                    MessageBox.Show("KHÔNG TỒN TẠI VTPT: " + tkObj.MaThietBi);
                                    return;
                                }
                                oTTVT = new TRANG_THAI_VTPT();
                                oTTVT = ttvtCtrl.usp_SelectTRANG_THAI_VTPTByMaTrangThai(tkObj.MaTrangThai);
                                if (oTTVT != null)
                                {
                                    tkObj.TenTrangThai = oTTVT.TenTrangThai;
                                    chkKhonghople.Checked = false;
                                    this.cmdLuu.Enabled = true;
                                }
                                else
                                {
                                    chkKhonghople.Checked = true;
                                    this.cmdLuu.Enabled = false;
                                    return;
                                }
                            }
                            else
                            {
                                chkKhonghople.Checked = true;
                                this.cmdLuu.Enabled = false;
                                return;
                            }

                            if (iSLQuet > -1)
                            {
                                tkObj.SoLuong = float.Parse(arrvalue[iSLQuet].ToString());// so luong xuat                                                        
                            }
                            else
                            {
                                chkKhonghople.Checked = true;
                                this.cmdLuu.Enabled = false;
                                return;
                            }

                            // kiem tra luong ton kho
                            float soluongton = 0;
                            clsCHI_TIET_KHO ctKhoCtrl = new clsCHI_TIET_KHO(_sConn);
                            CHI_TIET_KHO ctKhoObj = new CHI_TIET_KHO();
                            List<CHI_TIET_KHO> lstCTKho = new List<CHI_TIET_KHO>();
                            ctKhoObj.MaThietBi = tkObj.MaThietBi;
                            ctKhoObj.MaKho = tkObj.MaKho;
                            ctKhoObj.MaTrangThai = tkObj.MaTrangThai;

                            lstCTKho = ctKhoCtrl.usp_SelectCHI_TIET_KHO(ctKhoObj);
                            if (lstCTKho.Count == 1)
                            {
                                soluongton = float.Parse(lstCTKho[0].SoLuongTon.ToString());
                                // kiem tra xem VTPT nay co cac phieu xuat kho nao chua duoc duyet
                                List<CHI_TIET_PXH> lstctpxh = new List<CHI_TIET_PXH>();
                                clsCHI_TIET_PXH ctpxhCtrl = new clsCHI_TIET_PXH(_sConn);
                                lstctpxh = ctpxhCtrl.usp_CheckSoLuongXuatKhoChuaDuyet(tkObj.MaThietBi, tkObj.MaKho, tkObj.MaTrangThai);
                                for (int i = 0; i < lstctpxh.Count; i++)
                                {
                                    soluongton -= lstctpxh[i].SoLuong;
                                }
                            }
                            else
                            {
                                if (lstCTKho.Count > 1)
                                {
                                    this.cmdLuu.Enabled = false;
                                    MessageBox.Show("DỮ LIỆU TỒN KHO (TABLE CHI_TIET_KHO) BỊ TRÙNG DỮ LIỆU");
                                    return;
                                }
                            }

                            int k = lstCTpxh.FindIndex(delegate(CHI_TIET_PXH x) { return x.MaThietBi == tkObj.MaThietBi && x.MaTrangThai == tkObj.MaTrangThai && x.MaKho == tkObj.MaKho; });
                            if (k < 0)
                            {

                                if (soluongton >= tkObj.SoLuong)
                                {
                                    lstCTpxh.Add(tkObj);
                                }
                            }
                            else
                            {
                                if (soluongton - lstCTpxh[k].SoLuong >= tkObj.SoLuong)

                                    lstCTpxh[k].SoLuong += tkObj.SoLuong;
                            }
                            #endregion Doc tung dong noi dung file
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("KHÔNG THỂ NẠP ĐƯỢC DỮ LIỆU TỪ FILE.\nĐỊNH DẠNG FILE CHƯA ĐÚNG");
                        return;
                    }
                }// end while



                // remove khỏi lstCTpxh các VTPT không nằm trong PO hoac co so luong > hon so luong trong PO
                List<CHI_TIET_PDH> lstCT = new List<CHI_TIET_PDH>();
                lstCT = (List<CHI_TIET_PDH>)this.gridControl1.DataSource;
                if (lstCT != null && lstCT.Count > 0)
                {
                    float sl = 0;
                    for (int i = 0; i < lstCTpxh.Count; i++)
                    {
                        sl = 0;
                        for (int j = 0; j < lstCT.Count; j++)
                        {
                            if (lstCT[j].MaThietBi == lstCTpxh[i].MaThietBi && lstCT[j].MaTrangThai == lstCTpxh[i].MaTrangThai)
                            {
                                sl += lstCT[j].SoLuong;
                            }
                        }
                        if (sl == 0 || sl < lstCTpxh[i].SoLuong) // nếu không có trong PO hoặc sl lơn hon PO thì xóa đi
                        {
                            lstCTpxh[i].TinhTrang = 1;
                        }
                    }

                    this.gridControl2.DataSource = lstCTpxh;
                    this.gridControl2.RefreshDataSource();
                }
                else
                    MessageBox.Show("VUI LÒNG CHỌN PO ĐỂ XUẤT KHO");



            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                reader.Dispose();
            }
        }
            

        private void optThuCong_CheckedChanged(object sender, EventArgs e)
        {
            if (optThuCong.Checked == true)
            {
                this.cmdNapDuLieu.Enabled = false;
                this.cmdCapNhatSL.Enabled = true;
            }
        }

        private void optThietBi_CheckedChanged(object sender, EventArgs e)
        {
            if (this.optThietBi.Checked == true)
            {
                this.cboMobileDevice.Items.Clear();
                this.cmdNapDuLieu.Enabled = true;
                this.cmdCapNhatSL.Enabled = false;
                try
                {

                    RemoteDeviceManager devmng = new RemoteDeviceManager();                   
                    foreach (RemoteDevice dev in devmng.Devices)
                    {
                        this.cboMobileDevice.Items.Add(dev.Name);
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void cboMobileDevice_SelectedIndexChanged(object sender, EventArgs e)
        {
            // nap ten file
            try
            {
                this.cboFileName.Items.Clear();
                RemoteDeviceManager devmng = new RemoteDeviceManager();
                
                foreach (RemoteDevice dev in devmng.Devices)
                {
                    if (dev.Name == this.cboMobileDevice.Text.Trim())
                    {
                        rdev = dev;                       
                    }
                }
                if (rdev != null)
                {
                   // string myDocs = rdev.GetFolderPath(SpecialFolder.MyDocuments) + @"\KiemKho";
                    //string myDocs = @"\Temp\KiemKho";

                    string myDocs = "";

                    clsTHAM_SO tsCtrl = new clsTHAM_SO(_sConn);
                    THAM_SO tsObj = new THAM_SO();
                    tsObj = tsCtrl.SelectTHAM_SO("vPXK_Src"); // duong dan file se copy tu may kiem kho
                    if (tsObj != null && tsObj.DaXoa == 0)
                    {
                        myDocs = tsObj.GiaTri;
                    }

                   
                    string[] lstfile = RemoteDirectory.GetFiles(rdev, myDocs, "*.txt");
                    for (int i = 0; i < lstfile.Length; i++)
                    {
                        this.cboFileName.Items.Add(lstfile[i].ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void repositoryItemHyperLinkEdit1_Click(object sender, EventArgs e)
        {
            try
            {
                int index = this.gridView1.FocusedRowHandle;
                if (index >= 0)
                {
                    lstCTpxh.RemoveAt(index);
                    this.gridControl2.RefreshDataSource();
                }
            }
            catch { }
        }

        private void label10_Click(object sender, EventArgs e)
        {

        }

        private void cboFileName_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void label9_Click(object sender, EventArgs e)
        {

        }


        private string CatNoiDungFile(string filepath, string filename)
        {
            try
            {
                Stream r = File.Open(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                StreamReader reader = new StreamReader(r);


                clsTHAM_SO tsCtrl = new clsTHAM_SO(_sConn);
                THAM_SO tsObj = new THAM_SO();
                string giatri = "";
                string path = "";
                string returnFile = "";
                tsObj = tsCtrl.SelectTHAM_SO("vPXK_Template");
                if (tsObj != null && tsObj.DaXoa == 0)
                {
                    giatri = tsObj.GiaTri;
                }
                tsObj = new THAM_SO();
                tsObj = tsCtrl.SelectTHAM_SO("vPXK_Des");
                if (tsObj != null && tsObj.DaXoa == 0)
                {
                    path = tsObj.GiaTri;
                }

                int iMaKho = -1; // vị trí 

                iMaKho = Array.IndexOf(giatri.Split(','), "MaKho");

                if (iMaKho > -1 && path != "") // neu template co su dung scan so cmnd
                {

                    Dictionary<string, StreamWriter> dic = new Dictionary<string, StreamWriter>();
                    string socmnd = "";
                    StreamWriter w;
                    while (!reader.EndOfStream)
                    {

                        string line = reader.ReadLine();
                        string[] arrvalue = new string[10];
                        arrvalue = line.Split('\t');

                        socmnd = arrvalue[iMaKho].ToString();
                        if (socmnd != "")
                        {
                            if (dic.ContainsKey(socmnd))
                            {
                                dic[socmnd].WriteLine(line);
                            }
                            else
                            {
                                if (File.Exists(path + socmnd + "_" + filename))
                                    w = new StreamWriter(path + socmnd + "_" + filename, false);
                                else
                                    w = new StreamWriter(path + socmnd + "_" + filename, true);

                                w.WriteLine(line);
                                dic.Add(socmnd, w);
                            }
                        }
                    }

                    if (dic.Count > 0)
                    {
                        foreach (StreamWriter i in dic.Values)
                        {
                            i.Close();
                        }

                        if (dic.ContainsKey(frmDangNhap.objTaiKhoan._soCMND.Trim()))
                        {
                            returnFile = path + _nguoitao + "_" + filename;
                        }
                    }

                }
                else
                {

                }
                r.Close();
                r.Dispose();
                reader.Close();
                reader.Dispose();

                return returnFile;
            }
            catch (Exception ex)
            {
                return "";
            }

        }

       
    }
}